package com.example.fengyungo.filter;

import com.example.fengyungo.domain.pojo.LoginUser;
import com.example.fengyungo.exception.NotLoginException;
import com.example.fengyungo.exception.TokenErrorException;
import com.example.fengyungo.util.RedisCache;
import com.example.fengyungo.util.SpringContextUtils;
import com.example.fengyungo.util.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // log.info("doFilterInternal");
        // 获取token
        String token = request.getHeader("token");
        // log.info("token="+token);

        if (!StringUtils.hasText(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 用于全局异常处理
        HandlerExceptionResolver handlerExceptionResolver = SpringContextUtils.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);

        // 解析token
        String userid;
        try {
            // Claims claims = JwtUtil.parseJWT(token).getBody();
            Claims claims = TokenUtil.parseClaim(token).getPayload();
            userid = (String) claims.get("token");
        } catch (Exception e) {
            e.printStackTrace();
            handlerExceptionResolver.resolveException(request, response, null, new TokenErrorException("token非法"));
            return;
        }
        // 从redis中获取用户信息
        String redisKey = "login:" + userid;
        // log.info("redisKey="+redisKey);
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            handlerExceptionResolver.resolveException(request, response, null, new NotLoginException("用户未登录"));
            return;
        }
        // 存入SecurityContextHolder
        // TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
